package com.amado.course50java8;

import java.util.Optional;
import java.util.OptionalLong;
import java.util.function.Function;

public class Java806Optional3 {
    public static void main(String[] args) {
        System.out.println(Optional.ofNullable(null).orElse("cccc"));
        System.out.println(Optional.ofNullable("BBB").orElse("cccc"));
        Optional.ofNullable(null).map(e -> {
            System.out.println("aaaaaaaaaaaaaaaaaaa");
            return true;
        });
        // 参数不能是null
        Optional<String> optionalOf = Optional.of("a");
        // 参数可以是null与非null
        Optional<String> optionalOfNullable = Optional.ofNullable("C");

        //如果Optional中有一个值，返回值，否则抛出 NoSuchElementException
        System.out.println(optionalOfNullable.get());

//		void ifPresent(Consumer<? super T> consumer)
//		If a value is present, invoke the specified consumer with the value, otherwise do nothing.
        optionalOfNullable.ifPresent((e) -> System.out.println());
        //Return true if there is a value present, otherwise false.
        //返回 true如果存在值，否则为 false
        System.out.println(optionalOf.isPresent());
        System.out.println(optionalOfNullable.isPresent());
//		<U> Optional<U>	map(Function<? super T,? extends U> mapper)
//		If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result.
        //如果存在一个值，则应用提供的映射函数，如果结果不为空，则返回一个 Optional结果的 Optional
        optionalOfNullable.map(new Function<String, String>() {
            @Override
            public String apply(String t) {
                return t;
            }
        });


        Stu stu = null;
        Optional<Stu> stuOptional = Optional.ofNullable(stu);
        System.out.println(stuOptional.map(Stu::getAddr).orElse("addr"));
        System.out.println(stuOptional.map(Stu::getName).orElse("name"));

        Stu stuOne = new Stu();
        stuOne.setAddr("addrs");
        Optional<Stu> stuOptional2 = Optional.ofNullable(stuOne);
        System.out.println(stuOptional2.map(Stu::getAddr).orElse("addr1"));
        System.out.println(stuOptional2.map(Stu::getName).orElse("name2"));
    }

    static class Stu {
        private String name;
        private String addr;

        public String getAddr() {
            return addr;
        }

        public void setAddr(String addr) {
            this.addr = addr;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
